package com.yuyou.fn.cas;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.jasig.cas.client.authentication.AuthenticationRedirectStrategy;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Properties;

public class CasRedirectStrategy implements AuthenticationRedirectStrategy {


    @Override
    public void redirect(HttpServletRequest request, HttpServletResponse response, String potentialRedirectUrl) throws IOException {

        String requestURI = request.getRequestURI();


        if (requestURI.contains("bridge")) {
            Properties applicationConfig = (Properties) WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("applicationConfig");
            String dev = applicationConfig.getProperty("dev");
            int s = requestURI.indexOf("bridge") + 7;
            int e = requestURI.indexOf("bridge", s) - 1;
            String loginInfoStr = requestURI.substring(s, e) ;
            JSONObject loginInfo = JSONObject.parseObject( new String( Base64.decodeBase64(loginInfoStr.getBytes("utf-8")) ,"utf-8" ) );
            String loginWay = loginInfo.getString("loginWay");
            String rUrl = applicationConfig.getProperty("cas.ucUrlPrefix");
            if (loginWay.equalsIgnoreCase("sms")) {
                rUrl += "smsLogin?systemId=23";
            } else if (loginWay.equalsIgnoreCase("wx")) {
                rUrl += "wechat/wechatScan?systemId=23";
                if (Boolean.valueOf(dev)) {
                    rUrl += "&wechatType=3";
                } else {
                    rUrl += "&wechatType=2";
                    int wechatType = 2;
                    if (rUrl.contains("zytest")) {
                        wechatType = 3;
                    } else if (rUrl.contains("pre-")) {
                        wechatType = 4;
                    }
                    rUrl += "&wechatType=" + wechatType;
                }
            }
            rUrl += "&redirectUrl=" + URLEncoder.encode(applicationConfig.getProperty("cas.casServerUrlPrefix")+"login?service="+request.getRequestURL().toString()+"&getexecution=true" ,"utf-8") ;
            response.sendRedirect(rUrl);
        } else {
            response.sendRedirect(potentialRedirectUrl);
        }


    }
}
